const http = require("http");
const app = require("./module/router")
const ejs = require("ejs");
const { MongoClient } = require("mongodb");
const querystring = require("querystring");

const url = "mongodb://127.0.0.1:27017/";
// const url = "mongodb://admin:admin123@127.0.0.1:27017"; // 使用MongoDB的连接字符串格式
const dbName= "itying";
// const client = new MongoClient(url,{ useUnifiedTopology: true }); // 再次刷新会报错，需使用 MongoClient.connect(url, (err, client) => {}) 方式连接数据库

// 注册web服务
http.createServer(app).listen(3000);

console.log('Server running at http://127.0.0.1:3000/');

app.static("static");  // 修改默认静态web目录

// 配置路由
app.get("/", function(req, res) {
  MongoClient.connect(url, { useUnifiedTopology: true }, (err, client) => {
    if(err) {
      console.log(`err`, err);
      return;
    }
    let db = client.db(dbName);
    // 查询数据
    db.collection("user").find({}).toArray((err, result) => {
      if(err) {
        console.log(`err`, err);
        return;
      }
      console.log(`result`, result);
      client.close();
      ejs.renderFile("./views/index.ejs", { list: result }, (err, data) => {
        res.send(data);
      })
    })
  })
})

app.get("/register", function(req, res) {
  ejs.renderFile("./views/register.ejs", {}, (error, data) => {
    res.send(data);
  })
})

app.post("/doRegister", function(req, res) {
  let body = querystring.parse(req.body);
  console.log(`body`, body);
  MongoClient.connect(url, { useUnifiedTopology: true }, (err, client) => {
    if(err) {
      console.log(`err`, err);
      return;
    }
    let db = client.db(dbName);
    // 插入数据
    db.collection("user").insertOne(body, (err, result) => {
      if(err) {
        console.log(`err`, err);
        return;
      }
      console.log(`result`, result);
      client.close();
      res.send("注册  成功");
    })
  })
})